import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
import Homepage from '../components/homepage/Homepage'
import Notifications from '../components/notifications/Notifications'
import Subscriptions from '../components/subscriptions/Subscriptions'
import Search from '../components/search/Search'
import User from '../components/user/User'
import Write from '../components/write/Write'
import RecommendItem from "../components/subscriptions/parts/right/parts/recommend/RecommendItem";
import CommonItem from "../components/subscriptions/parts/right/parts/common/CommonItem";
import Login from "../views/Login";
import Posts from "../components/posts/Posts";

Vue.use(VueRouter);

  const routes = [
    {path: '/home',name: 'home',redirect: '/'},
    {
      path: '/',name: 'home',component: Home,
      children: [
        {path: '/',component: Homepage},
        {path: '/subscriptions',component: Subscriptions,redirect:'/subscriptions/recommend',
          children: [
            {path: '/subscriptions/recommend',component: RecommendItem},
            {path: '/subscriptions/common/:id',component: CommonItem},  /*动态匹配*/
          ],
        },
        {path: '/notifications',component: Notifications},
        {path: '/search',component: Search},
        {path: '/p/:hash/',name: 'posts',component: Posts,},

      ],

    },
    {path: '/user',name: 'user',component: User,
      //局部路由
      beforeEnter: (to, from, next) => {
        const token = window.sessionStorage.getItem('token');
        if (!token) return next('/login');    //如果没有token则强制跳转login
        next();
      },
      beforeLeave: (to, from, next) => {
        console.log('to leave');
        next();
      }
    },
    {path: '/write',name: 'write',component: Write,},
    {path: '/login',name: 'login',component: Login,
      beforeEnter: (to, from, next) => {
        const token = window.sessionStorage.getItem('token');
        if (token) return next('/');    //如果没有token则强制跳转login
        next();
      },
    },

];

const router = new VueRouter({
  routes
});

//全局路由
router.beforeEach((to,from,next) => {
  next();
});

export default router
